﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Compiled.Win8StartWPF
{
	public class Shortcut
	{
		public Shortcut()
		{
		}

		public Shortcut(string LinkFileName)
		{
			this.FileName = LinkFileName;
			this.Name = Path.GetFileNameWithoutExtension(LinkFileName);
			this.Icon = GetIcon(LinkFileName);
		}

		private System.Drawing.Icon GetIcon(string FileName)
		{
			System.Drawing.Icon icon = null;
			if (File.Exists(FileName))
				icon = System.Drawing.Icon.ExtractAssociatedIcon(FileName);
			else
				icon = Properties.Resources.Folder;
			return icon;
		}

		public void Launch()
		{
			if (!IsLink)
			{
				Process proc = new Process();
				proc.StartInfo.FileName = FileName;
				proc.Start();
			}
			else
			{
				LaunchShortcut();
			}
		}

		/// <summary>
		/// Decide whether to browse inside of folders. When True, clicking on a folder
		/// will open a folder in this panel. When false, clicking a folder will open 
		/// Windows Explorer to the specified location.
		/// </summary>
		public bool BrowseFolders
		{
			get;
			set;
		}

		public string FileName
		{
			get;
			set;
		}

		public string Name
		{
			get;
			set;
		}

		public DateTime LastLaunch
		{
			get
			{
				return DateTime.MinValue;
			}
		}

		private System.Drawing.Icon _icon;
		public System.Drawing.Icon Icon
		{
			get { return _icon; }
			set { _icon = value; }
		}

		public bool IsFolder
		{
			get
			{
				return Directory.Exists(FileName);
			}
		}

		public bool IsLink
		{
			get
			{
				return (Path.GetExtension(FileName) == ".lnk");
			}
		}

		private void LaunchShortcut()
		{
			// Code to resolve (x86) issue on 64 bit systems. This should not occur if you compile for 64-bit systems
			Shell32.Shell shell = new Shell32.Shell();
			Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(FileName));
			Shell32.FolderItem folderItem = folder.Items().Item(Path.GetFileName(FileName));
			Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;

			link.Resolve(0x1 | 0x8 | 0x10); // Resolve( NULL, SLR_NO_UI | SLR_NOUPDATE | SLR_NOSEARCH )
			string exeFileName = link.Path;

			System.Diagnostics.Debug.WriteLine(link.WorkingDirectory);
			try
			{
				System.Diagnostics.Debug.WriteLine("Launching: " + exeFileName);
				if (File.Exists(exeFileName) || Directory.Exists(exeFileName))
					shell.ShellExecute(exeFileName);
				else
					shell.ShellExecute(exeFileName.Replace(" (x86)", ""));
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		public override string ToString()
		{
			return Path.GetFileNameWithoutExtension(FileName);
		}
	}
}
